package com.mall.exception;

import com.mall.common.model.GlobalResponse;
import com.mall.enums.GlobalResponseEnum;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Objects;

@ControllerAdvice
public class RuntimeExceptionHandler {

    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public GlobalResponse handle(RuntimeException e){
        return GlobalResponse.error(GlobalResponseEnum.ERROR,e.getMessage());
    }

    @ExceptionHandler(UserLoginException.class)
    @ResponseBody
    public GlobalResponse userLoginHandler(){
        return GlobalResponse.error(GlobalResponseEnum.NEED_LOGIN);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public GlobalResponse noValidExceptionHandle(MethodArgumentNotValidException e){
        BindingResult bindingResult = e.getBindingResult();
        Objects.requireNonNull(bindingResult.getFieldError()).getField();
        return GlobalResponse.error(GlobalResponseEnum.PARAM_ERROR
                , bindingResult.getFieldError().getField()+" "+ bindingResult.getFieldError().getDefaultMessage());
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseBody
    public GlobalResponse messageNotReadableExceptionHandle(HttpMessageNotReadableException e){
        return GlobalResponse.error(GlobalResponseEnum.JSON_FORMAT_ERROR);
    }
}
